<?php

/**
 * +----------------------------------------------------------------------
 * | 后台登录主控制器类
 * | [GeeTest极验行为验4.0管理后台系统](https://console.geetest.com/sensbot/management)
 * | 后台登录手势验证码，支持cmf6
 * +----------------------------------------------------------------------
 *                                            ...     .............
 *                                          ..   .:!o&*&&&&&ooooo&; .
 *                                        ..  .!*%*o!;.
 *                                      ..  !*%*!.      ...
 *                                     .  ;$$!.   .....
 *                          ........... .*#&   ...
 *                                     :$$: ...
 *                          .;;;;;;;:::#%      ...
 *                        . *@ooooo&&&#@***&&;.   .
 *                        . *@       .@%.::;&%$*!. . .
 *          ................!@;......$@:      :@@$.
 *                          .@!   ..!@&.:::::::*@@*.:..............
 *        . :!!!!!!!!!!ooooo&@$*%%%*#@&*&&&&&&&*@@$&&&oooooooooooo.
 *        . :!!!!!!!!;;!;;:::@#;::.;@*         *@@o
 *                           @$    &@!.....  .*@@&................
 *          ................:@* .  ##.     .o#@%;
 *                        . &@%..:;@$:;!o&*$#*;  ..
 *                        . ;@@#$$$@#**&o!;:   ..
 *                           :;:: !@;        ..
 *                               ;@*........
 *                       ....   !@* ..
 *                 ......    .!%$! ..     | AUTHOR: dfer
 *         ......        .;o*%*!  .       | EMAIL: df_business@qq.com
 *                .:;;o&***o;.   .        | QQ: 3504725309
 *        .;;!o&****&&o;:.    ..          | WEBSITE: http://www.dfer.site
 * +----------------------------------------------------------------------
 *
 */

namespace plugins\dfer_thinkcmf_tools\controller;

use think\facade\Db;
use cmf\controller\PluginBaseController;
use plugins\dfer_thinkcmf_tools\lib\GeetestLib;
use app\admin\model\UserModel;
use app\admin\model\RoleUserModel;

class AdminLoginController extends BaseController
{

	/**
	 * 登录验证
	 */
	public function doLogin()
	{
		if (!$this->request->isPost()) {
			$this->error('非法登录!');
		}

		$loginAllowed = session("__LOGIN_BY_CMF_ADMIN_PW__");
		if (empty($loginAllowed)) {
			$this->error('非法登录!', cmf_get_root() . '/');
		}

		$this->geetestInit();

		$name = $this->request->param("username");
		if (empty($name)) {
			$this->error(lang('USERNAME_OR_EMAIL_EMPTY'));
		}
		$pass = $this->request->param("password");
		if (empty($pass)) {
			$this->error(lang('PASSWORD_REQUIRED'));
		}
		if (strpos($name, "@") > 0) { //邮箱登陆
			$where['user_email'] = $name;
		} else {
			$where['user_login'] = $name;
		}

		$result = UserModel::where($where)->find();

		if (!empty($result) && $result['user_type'] == 1) {
			if (cmf_compare_password($pass, $result['user_pass'])) {
				$groups = RoleUserModel::alias("a")
					->join('role b', 'a.role_id =b.id')
					->where(["user_id" => $result["id"], "status" => 1])
					->value("role_id");
				if ($result["id"] != 1 && (empty($groups) || empty($result['user_status']))) {
					$this->error(lang('USER_DISABLED'));
				}
				//登入成功页面跳转
				session('ADMIN_ID', $result["id"]);
				session('name', $result["user_login"]);
				$data                    = [];
				$data['last_login_ip']   = get_client_ip(0, true);
				$data['last_login_time'] = time();
				$token                   = cmf_generate_user_token($result["id"], 'web');
				if (!empty($token)) {
					session('token', $token);
				}
				UserModel::where('id', $result['id'])->update($data);
				cookie("admin_username", $name, 3600 * 24 * 30);
				session("__LOGIN_BY_CMF_ADMIN_PW__", null);
				$this->success(lang('LOGIN_SUCCESS'), url("admin/Index/index"), ['token' => $token, 'user' => [
					'id'            => $result['id'],
					'user_login'    => $result['user_login'],
					'user_nickname' => $result['user_nickname'],
				]]);
			} else {
				$this->error(lang('PASSWORD_NOT_RIGHT'));
			}
		} else {
			$this->error(lang('USERNAME_NOT_EXIST'));
		}
	}


	/**
	 * 初始化
	 * @param {Object} $var 变量
	 **/
	public function geetestInit($var = null)
	{
		$config = $this->config;
		$GtSdk = new GeetestLib($config['captcha_id'], $config['private_key']);
		$data = [
			"user_id" => session('user_id'),
			"client_type" => "web",
			"ip_address" => get_client_ip()
		];
		$geetest_challenge = $this->request->param('geetest_challenge');
		$geetest_validate = $this->request->param('geetest_validate');
		$geetest_seccode = $this->request->param('geetest_seccode');
		if (session('gtserver') == 1) {   //服务器正常
			$result = $GtSdk->success_validate(
				$geetest_challenge,
				$geetest_validate,
				$geetest_seccode,
				$data
			);
			if (!$result) {
				$this->error(lang('CAPTCHA_NOT_RIGHT'));
			}
		} else {  //服务器宕机,走failback模式
			$result = $GtSdk->fail_validate(
				$geetest_challenge,
				$geetest_validate,
				$geetest_seccode
			);
			if (!$result) {
				$this->error(lang('CAPTCHA_NOT_RIGHT'));
			}
		}
	}

	/**
	 * 验证码初始化
	 */
	public function startCaptcha()
	{
		//error_reporting(0);

		$config = $this->config;

		$GtSdk = new GeetestLib($config['captcha_id'], $config['private_key']);
		$data = [
			"user_id" => mt_rand(100000, 999999),
			"client_type" => "web",
			"ip_address" => get_client_ip()
		];

		$status = $GtSdk->pre_process($data, 1);
		session('gtserver', $status);
		session('user_id', $data['user_id']);
		return $GtSdk->get_response_str();
	}
}
